package com.lzh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzh.ThreadLocalUtils;
import com.lzh.bean.Customer;

import com.lzh.bean.User1;
import com.lzh.bean.UserType;
import com.lzh.common.bean.PageBean;
import com.lzh.common.curd.impl.BaseServiceImpl;
import com.lzh.common.ex.BusinessException;
import com.lzh.common.utils.Assert;
import com.lzh.mapper.CustomerMapper;
import com.lzh.mapper.UserMapper1;
import com.lzh.query.CustomerQuery;
import com.lzh.query.UserQuery;
import com.lzh.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

@Service
public class CustomerServiceImpl extends BaseServiceImpl<Customer, CustomerMapper> implements CustomerService {

    @Autowired(required = false)
    UserMapper1 userMapper1;
    @Autowired
    private CustomerMapper customerMapper;


    /**
     * 保存用户
     * @param entity
     * @return
     */
    @Transactional
    @Override
    public int save(Customer entity) {
        int c =userMapper1.queryUserByUserName(entity.getAccount());
        if (c>0) throw new BusinessException("该账号已经存在！");
        //获取线程内容
        Map map = ThreadLocalUtils.getInstance().get();
        int id = Integer.parseInt(map.get("id").toString());
        entity.setSaleId(id);
        ThreadLocalUtils.getInstance().remove();
        //先保存用户
        User1 user1 = new User1(entity.getAccount(),entity.getPassword(), UserType.CUSTOMER_USER);
        int save = userMapper1.save(user1);
        Assert.isZerp(save,"保存用户失败");
        //保存客户
        //主键返回获取设置客户id
        entity.setId(user1.getId());

        return super.save(entity);
    }

    /**
     * 删除客户
     * @param id
     * @return
     */
    @Override
    public int delete(Serializable id) {
        //
        int delete = customerMapper.delete(id);
        Assert.isZerp(delete,"删除用户失败");
        return delete;
    }


    /**
     * 分页查询
     * @param query
     * @return
     */
    @Override
    public PageBean query(CustomerQuery query) {
        //分页查询
        PageHelper.startPage(query.getPage(), query.getPageSize());//后面紧跟查询
        List list = baseMapper.query(query);
        PageInfo info = new PageInfo(list);
        return new PageBean(query.getPage(), query.getPageSize(), info.getTotal(), list);
    }
}
